package org.ala.tiktools.redis.config;


import org.ala.tiktools.logs.LoggerFactory;
import org.ala.tiktools.redis.RedisTool;
import org.slf4j.Logger;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.*;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;

import java.util.Map;

/**
 * @author ala
 * @date 2024-11-27 15:10
 */
public class RedisBeanRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor, EnvironmentAware {


    static Logger log = LoggerFactory.getLogger("tiktools", "redis-init");


    protected Environment env;

    @Override
    public void setEnvironment(Environment environment) {
        env = environment;
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
    }

    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry beanDefinitionRegistry) throws BeansException {
        //  解析配置项
        Configuration configuration = new Configuration();
        Map<String, ConfigItem> map = configuration.parse(env);
        if (map == null || map.isEmpty()) {
            log.info("[RedisBeanRegistryPostProcessor postProcessBeanDefinitionRegistry] 没有找到任何redis配置项.");
            return;
        }

        map.forEach((k,v) -> registerBeanDefinition(k, v, beanDefinitionRegistry));
    }
    /**
     * 注册RedisTool的BeanDefine
     */
    protected void registerBeanDefinition(String name, ConfigItem item, BeanDefinitionRegistry registry) {
        BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(RedisTool.class);
        builder.addPropertyValue("config", item);
        builder.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE);

        String beanName = Configuration.PREFIX_BEAN_NAME + "_" + name;

        BeanDefinition beanDefinition = builder.getBeanDefinition();
        beanDefinition.setPrimary(true);

        BeanDefinitionHolder holder = new BeanDefinitionHolder(beanDefinition, beanName);
        BeanDefinitionReaderUtils.registerBeanDefinition(holder, registry);

        log.info("[RedisBeanRegistryPostProcessor registerBeanDefinition] 初始化RedisTool bean名称：" + beanName);
    }




}
